package smartlifev30.com.sdk.net.baiwei.protocol;

/**
 * @author tys
 * @date 2018/8/12
 */

public class Header {
    /**
     * 固定协议头
     */
    public static final String HEAD_FEATURE = "@#$%";

    /**
     * 整条消息长度(4个字节)
     */
    public static final int HEAD_DESCRIBE_LENGTH = 4;

    /**
     * 协议头长度(字节)。固定协议头长度 + 描述消息内容长度的字节数。
     */
    public static final int HEAD_LENGTH = HEAD_FEATURE.length() + HEAD_DESCRIBE_LENGTH;

    /**
     * 协议头检测
     *
     * @param bytes
     * @return
     */
    public static boolean check(byte[] bytes) {
        int length = bytes.length;
        if (length < Header.HEAD_LENGTH) {
            //不够协议头长度
            return false;
        }
        String headFeature = new String(bytes, 0, Header.HEAD_FEATURE.length());
        if (!Header.HEAD_FEATURE.equals(headFeature)) {
            //固定协议头不匹配
            return false;
        }
        int contentLength = getContentLength(bytes);
        //实际消息长度等于记录消息长度
        return contentLength <= length;
    }

    /**
     * 添加协议头.@#$%0012{}
     *
     * @param msg
     */
    public static String add(String msg) {
        return String.format("%s%s%s", HEAD_FEATURE, String.format("%04x",
                msg.length() + HEAD_LENGTH), msg);
    }

    public static int getContentLength(byte[] content) {
        if (content.length < Header.HEAD_LENGTH) {
            return -1;
        }
        String headMsgLength = new String(content, Header.HEAD_FEATURE.length(), Header.HEAD_DESCRIBE_LENGTH);
        int recodeLength = -1;
        try {
            recodeLength = Integer.valueOf(headMsgLength, 16);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return recodeLength;
    }

}
